/*
	FileName : app_i2c1.c
	Description : 
		EEPROM FM24CL04B.
	
	Created on 2013.10.15 by ZZP.
	
	Revision History:
	
*/

#include "bsp.h"
#include "app.h"
#include "miscfnx.h"
#include "app_i2c1.h"


REC_HEAD 		RecHead_A;
REC_HEAD 		RecHead_B;

#if APP_I2C_1_ENABLE
OS_EVENT    *Sem_WriteReadI2C1;		///deadlock
uint8_t		imageOfEEROM[512];
#endif

void  AppTaskI2C1 (void *p_arg)
{
	(void)p_arg;
	
	while (DEF_TRUE)
	{
		if (AppInfo.RdyFlag == 1)
		{
			//APP_I2C1_Test();
		}
		
		OSTimeDly(10);
	}
}

void APP_I2C1_WriteDebug(uint8_t index,uint8_t val)
{
	uint16_t crc;
	imageOfEEROM[index+496]=val;
	crc=Calc_CRCByte((uint8_t *)imageOfEEROM+496, 14);
	imageOfEEROM[510]=crc&0xff;
	imageOfEEROM[511]=(crc>>8)&0xff;
	APP_WriteI2C1(imageOfEEROM+496, 496, 16);
}

uint8_t APP_I2C1_Test(uint8_t *data)
{
	uint8_t *p,i,buf[16];
	uint16_t cnt,crc;

	p=buf;
	if(data!=0)
		p=data;

	cnt=16;
	APP_ReadI2C1(p, 496, &cnt);
	crc=Calc_CRCByte((uint8_t *)p, 14);
	if(crc!=p[14]+(p[15]<<8))
	{
		for(i=0;i<14;i++)
		{
			p[i]=0;
		}
		crc=Calc_CRCByte((uint8_t *)p, 14);
		p[14]=crc&0xff;
		p[15]=(crc>>8)&0xff;
	}

	cnt = 16;
	if(APP_WriteI2C1(p, 496, cnt))
		return 1;
	if(APP_ReadI2C1(p, 496, &cnt))
		return 2;
	if(cnt!=0)
		return 3;
	crc=Calc_CRCByte((uint8_t *)p, 14);
	if(crc!=p[14]+(p[15]<<8))
	{
		return 4;
	}
	return 0;
}


void clearEEromHead(uint8_t toClearData)
{
	if(toClearData)
	{
		OSSchedLock();
		RecHead_A.NextSector = 1;
		RecHead_A.TotNewRec = 0;
		RecHead_A.Crc = Calc_CRCByte((uint8_t *)&(RecHead_A.Flag[0]), 6);
		RecHead_B.NextSector = RecHead_A.NextSector;
		RecHead_B.TotNewRec = RecHead_A.TotNewRec;
		RecHead_B.Crc = RecHead_A.Crc;		
		OSSchedUnlock();
		APP_WriteI2C1((uint8_t *)&(RecHead_A.Flag[0]), 0, sizeof(REC_HEAD));	
		APP_WriteI2C1((uint8_t *)&(RecHead_B.Flag[0]),sizeof(REC_HEAD), sizeof(REC_HEAD));	
	}
}

uint16_t I2CReadPowOffData(uint8_t *buf)
{
	int i,j;
	uint16_t curIndex=0,readAddr=0,totalCnt=0;

	OSSchedLock();
    totalCnt = RecHead_A.TotNewRec > MAX_POW_DATA_CNT ? MAX_POW_DATA_CNT:RecHead_A.TotNewRec;
	curIndex = RecHead_A.NextSector < 1 ? 1:RecHead_A.NextSector;
	if(totalCnt>15)
		totalCnt=15;
	for(i=0;i<totalCnt;i++)
	{
		readAddr=(((curIndex + 30 - 2 - i)%30) + 1) * 16;
		for(j=0;j<16;j++)
		{
			buf[i*16+j]=imageOfEEROM[(readAddr+j)%512];
		}
	}
	OSSchedUnlock();
	return 16 * totalCnt;
}

uint8_t APP_ReadI2C1(uint8_t *buf, uint16_t ReadAddr, uint16_t *NumByteToRead)
{
	uint8_t err,tmp;
	OSSemPend(Sem_WriteReadI2C1,0,&err);
	tmp = BSP_ReadI2C1(buf,ReadAddr,NumByteToRead);
	OSSemPost(Sem_WriteReadI2C1);
	return tmp;
}

uint8_t APP_WriteI2C1(uint8_t *buf, uint16_t WriteAddr, uint16_t NumByteToWrite)
{
	uint16_t i;
	uint8_t err,tmp;
	OSTimeDly(10);
	OSSemPend(Sem_WriteReadI2C1,0,&err);
	tmp = BSP_WriteI2C1(buf,WriteAddr,NumByteToWrite);
	for(i = 0;i < NumByteToWrite;i++)
	{
		imageOfEEROM[(i+WriteAddr)%512]=buf[i];
	}
	OSSemPost(Sem_WriteReadI2C1);
	return tmp;
}





